package com.ys;

import java.io.*;
import java.util.Arrays;
import java.util.List;

/**
 * @program: note
 * @description:
 * @author:
 * @create 2020-06-11 23:14
 **/
public class FileIOUtils {
    public static void write(String file, String content, boolean append) {
        FileOutputStream fileOutputStream = null;
        BufferedOutputStream bufferedOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream(new File(file), append);
            bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
            bufferedOutputStream.write(content.getBytes());
        }  catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                bufferedOutputStream.close();
                fileOutputStream.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }

    public static String read(String file) {
        FileInputStream fileInputStream = null;
        BufferedInputStream bufferedInputStream = null;
        try {
            fileInputStream = new FileInputStream(new File(file));
            bufferedInputStream = new BufferedInputStream(fileInputStream);

            byte[] buffer = new byte[1024];

            //从文件中按字节读取内容，到文件尾部时read方法将返回-1
            StringBuilder rtn = new StringBuilder();
            int bytesRead = 0;
            while ((bytesRead = bufferedInputStream.read(buffer)) != -1) {
                // 将读取的字节转为字符串对象
                String chunk = new String(buffer, 0, bytesRead);
                rtn.append(chunk);
            }
            return rtn.toString();
        }  catch (IOException e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                if (bufferedInputStream != null) {
                    bufferedInputStream.close();
                }
                if (null != fileInputStream) {
                    fileInputStream.close();
                }
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }

    public static List<String> readLines(String file) {
        String[] array = read(file).split("\n");
        return Arrays.asList(array);
    }

    public static void main(String[] args) {
        String rootDir = System.getProperty("user.dir");
        String fileSep = System.getProperty("file.separator");
        String file = rootDir + fileSep + "data" + fileSep + "test.txt";

//        write(file, "Hello World\nAgain and Again\n", true);
//        read(file);
//        System.out.println(readLines(file));
    }
}
